package com.atguigu.chapter11.function;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.TableAggregateFunction;
import org.apache.flink.util.Collector;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/21 9:32
 */
public class Flink04_Function_TableAgg {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        Table table = tEnv.fromDataStream(waterSensorStream);
        // 1. table API中使用
        // 1.1 使用内联方式
        table
            .groupBy($("id"))
            .flatAggregate(call(MyTableAgg.class, $("vc")).as("value"))
            .select($("id"), $("value"))
            .execute()
            .print();
        // 1.2 注册之后使用
        // 略
        
        // 2. 在sql中使用
        
    }
    
    public static class FirstSecond {
        public Integer first = 0;
        public Integer second = 0;
    }
    
    public static class MyTableAgg extends TableAggregateFunction<String, FirstSecond> {
        
        // 初始化累加器
        @Override
        public FirstSecond createAccumulator() {
            return new FirstSecond();
        }
        
        // 聚合
        public void accumulate(FirstSecond acc, Integer vc) {
            if (vc > acc.first) {
                acc.second = acc.first;
                acc.first = vc;
            } else if (vc > acc.second) {
                acc.second = vc;
            }
        }
        
        // 发射数据
        public void emitValue(FirstSecond acc, Collector<String> out) {
            out.collect("最大: " + acc.first);  // 调用一次得到一样
            out.collect("次大: " + acc.second);
        }
    }
    
}
/*
每来一个水位: 输出 top2的水位

 */


